package com.zhss.security.demospringsecurity.config.filter;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName VerficationCodeFilter
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/9/14 15:45
 * @Version 1.0
 */
public class VerficationCodeFilter extends UsernamePasswordAuthenticationFilter {

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException(
					"Authentication method not supported: " + request.getMethod());
		}

		String kaptcha = request.getParameter("kaptcha");
		final String sessionKaptcha = (String) request.getSession().getAttribute("kaptcha");
		if (StringUtils.isEmpty(kaptcha) || StringUtils.isEmpty(sessionKaptcha) || !kaptcha.equalsIgnoreCase(sessionKaptcha)) {
			throw new AuthenticationServiceException("验证码输入错误");
		}
		return super.attemptAuthentication(request, response);
	}
}
